<template>
  <el-dialog @open="onDialogOpen" top="25vh" :model-value="props.visible" @close="onClose" :title="t('flypass.set_issuer')" width="600px">
    <el-form label-position="top">
      <el-form-item :label="t('flypass.select_issuer')">
        <el-select v-model="merchantId" class="w-full">
          <el-option v-for="item in merchantList" :key="item.mrchId" :value="item.mrchId" :label="item.name"></el-option>
        </el-select>
      </el-form-item>
    </el-form>  
    <template #footer>
      <div class="text-right">
        <el-button @click="onClose">{{ t('common.cancel') }}</el-button>
        <el-button type="primary" @click="confirm" :loading="loading">{{ t('common.confirm') }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>
  
<script lang='ts' setup>
import { getMerchantPage, Merchant } from '@/api/merchant'
import { setMerchantTopic } from '@/api/topic/topic';
import { ElMessage } from '@toms/element-ui';

const { t } = useI18n()
const merchantList = ref<Merchant[]>([])
const merchantId = ref<number | null>(null)
const loading = ref(false)
const props = defineProps<{topicId: number | null, visible: boolean}>()
const emit = defineEmits(['save', 'update:visible'])

async function onDialogOpen() {
  debugger
  const { data } = await getMerchantPage({pageNo: 1, pageSize: 100}) 
  merchantList.value = data  
}

async function confirm() {
  if(!props.topicId) {
    console.error('topicId is null')
    return
  }
  if(merchantId.value) {
    loading.value = true
    try {
      await setMerchantTopic({
      mrchId: merchantId.value,
      topicId: props.topicId
      })
    } catch(e: any) {
      ElMessage({
        type: 'error',
        message: e.message
      })
      loading.value = false
      return
    }    
    loading.value = false
    ElMessage({
      type: 'success',
      message: t('common.message.operation_success')
    })
    emit('save')
    emit('update:visible', false)
  }
}

function onClose() {
  merchantId.value = null
  emit('update:visible', false)
}

</script>
  
<style lang='stylus' scoped></style>
  